<?php

namespace App\Http\Controllers\Api\V2;

use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;
use Dingo\Api\Exception\ValidationHttpException;
use Elasticsearch\ClientBuilder;

class BaseController extends Controller
{
    // 接口帮助调用
    use Helpers;
	
	protected $imageBaseUrl;
	public function __construct() {
		$this->imageBaseUrl = env('CUT_IMAGE_UTL');
	}

    // 返回错误的请求
    protected function errorBadRequest($validator)
    {
        // github like error messages
        // if you don't like this you can use code bellow
        //
        //throw new ValidationHttpException($validator->errors());

        $result = [];
        $messages = $validator->errors()->toArray();

        if ($messages) {
            foreach ($messages as $field => $errors) {
                foreach ($errors as $error) {
                    $result[] = [
                        'field' => $field,
                        'code' => $error,
                    ];
                }
            }
        }

        throw new ValidationHttpException($result);
    }
	
	// 返回错误的json
	protected function returnError($validator, $all = false)
	{
	    $result = [];
		$msg = '';
	    $messages = $validator->errors()->toArray();
	
	    if ($messages) {
	        foreach ($messages as $field => $errors) {
	            foreach ($errors as $error) {
	                $result[] = [
	                    'field' => $field,
	                    'code' => $error,
	                ];
					if($all){
						$msg .= $error."\n";
					}else{
						$msg = $error;
						break 2;
					}
	            }
	        }
	    }
		return $this->returnFail($msg, $result);
	}
	
	protected function returnSuccess($data = [], $msg = 'success') {
		return array(
			'code' => 0,
			'msg'  => $msg,
			'data' => $data
		);
	}
	/**
	 * 错误返回
	 * 
	 */
	protected function returnFail($msg = 'fail', $data = []) {
		return array(
			'code' => 1,
			'msg'  => $msg,
			'data' => $data
		);
	}
	
	/**
	 * 获取商铺 与 当前用户的距离
	 * @param {Object} $id
	 * @param {Object} $longitude
	 * @param {Object} $latitude
	 */
	protected function getShopDistance($id, $longitude, $latitude)
	{
		$hosts    = array(env('ELASICSEARCHHOST'));
		$client   = ClientBuilder::create()->setHosts($hosts)->build();
		$must     = [
					'match' => [
						'_id' => $id
					]
				];
		$query    = [
			'bool' => [
				'filter' => [
					"geo_distance" => [
						"distance" => "10000km",
						"location" => [
							"lat" => $latitude,
							"lon" => $longitude
						]
					]
				]
			]
		];
		$sort = [
			"_geo_distance" => [
				"location" => [
					"lat" => $latitude,
					"lon" => $longitude
				],
				"order" => "asc",
				"unit" => "km"
			]
		];
		$query['bool']['must'] = $must;
		$sort = [
			"_geo_distance" => [
				"location" => [
					"lat" => $latitude,
					"lon" => $longitude
				],
				"order" => "asc",
				"unit" => "km"
			]
		];
		$params   = [
			'index' => 'cut_shop',
			'type'  => '_doc',
			'body'  => [
				'query' => $query,
				'sort'  => $sort
			]
		]; 
		$response = $client->search($params);
		$shop_ids = [];
		$shopHits = $response['hits']['hits'];
		if (isset($shopHits[0]['sort'][0])) {
			return \round($shopHits[0]['sort'][0],4);
		}
		return -1; // error
	}
}
